package math;

import org.springframework.beans.factory.support.ManagedList;

import java.util.*;

/**
 * Created by zhoub on 2020/3/24.
 */
public class LinearRegression {
    public static Map<String,Object> calculate(List<Map<String,Object>> list){
        Map<String,Object> map = new LinkedHashMap<>();
        int MAXN = list.size();
        int n = 0;
        double[] x = new double[MAXN];
        double[] y = new double[MAXN];
        double sumx = 0.0, sumy = 0.0, sumx2 = 0.0;
        for (Map<String,Object> item:list){
            //这里是x轴的参数
            x[n] = Double.parseDouble(item.get("rank").toString());
            //这里是y轴的参数
            y[n] = Double.parseDouble(item.get("qty").toString());
            sumx  += x[n];
            sumx2 += x[n] * x[n];
            sumy  += y[n];
            n++;
        }
        double xbar = sumx / n;
        double ybar = sumy / n;

        // second pass: compute summary statistics
        double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
        for (int i = 0; i < n; i++) {
            xxbar += (x[i] - xbar) * (x[i] - xbar);
            yybar += (y[i] - ybar) * (y[i] - ybar);
            xybar += (x[i] - xbar) * (y[i] - ybar);
        }
        double beta1 = xybar / xxbar;
        double beta0 = ybar - beta1 * xbar;

        // print results
        System.out.println("y   = " + beta1 + " * x + " + beta0);

        // analyze results
        int df = n - 2;
        double rss = 0.0;      // residual sum of squares
        double ssr = 0.0;      // regression sum of squares
        for (int i = 0; i < n; i++) {
            double fit = beta1*x[i] + beta0;
            rss += (fit - y[i]) * (fit - y[i]);
            ssr += (fit - ybar) * (fit - ybar);
        }
        double R2    = ssr / yybar;

        System.out.println("R2  = "+R2);

        map.put("r",R2);
        map.put("a",beta1);
        map.put("b",beta0);
        return map;
    }

    public static void main(String[] args){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("rank","0.29");
        map1.put("qty","0.00");
        list.add(map1);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("rank","86.59");
        map2.put("qty","99.00");
        list.add(map2);

        Map<String,Object> map3 = new HashMap<>();
        map3.put("rank","69.38");
        map3.put("qty","79.00");
        list.add(map3);

        Map<String,Object> map4 = new HashMap<>();
        map4.put("rank","51.99");
        map4.put("qty","59.00");
        list.add(map4);

        Map<String,Object> map5 = new HashMap<>();
        map5.put("rank","34.64");
        map5.put("qty","39.00");
        list.add(map5);

        Map<String,Object> map6 = new HashMap<>();
        map6.put("rank","17.37");
        map6.put("qty","19.00");
        list.add(map6);

        calculate(list);
    }

}
